import os
import wave
from io import BytesIO

import pyaudio
import requests
from fastapi import FastAPI, File, UploadFile, HTTPException, Response
import logging
import uvicorn

# 配置参数
class Config:
    FORMAT = pyaudio.paInt16  # 音频格式
    CHANNELS = 1  # 单声道
    RATE = 16000  # 采样率
    CHUNK = int(60 * 10 / 10 / 1000 * RATE * 2)  # 每帧的大小，根据你的stride计算
    COSY_VOICE_URL = 'http://localhost:50000/inference_sft'  # 假设的文本到语音服务URL
    SAMP_WIDTH = 2  # 采样宽度，16位为2，8位为1

config = Config()

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 初始化语音识别相关配置和对象
from speech_recognition import init_funasr_recognizer, funasr_speech_to_text

rcg = init_funasr_recognizer()

# 初始化对话历史列表
conversation_history = []

app = FastAPI()


# 语音AI交互系统的端点，调整入参为接收上传文件的形式，更符合接收音频数据的实际情况
@app.post("/voice-ai")
async def voice_ai_interaction(audio_file: UploadFile = File(...)):
    try:
        # 读取上传文件的音频字节数据
        audio_bytes = await audio_file.read()

        # 语音识别
        text = funasr_speech_to_text(audio_bytes, rcg, config)
        if not text:
            raise HTTPException(status_code=400, detail="语音识别失败，未获取到有效文本内容")
        logging.info(f"语音识别成功，文本内容: {text}")

        # 意图识别和对话管理
        from dialogue_management import qwen_intent_recognition
        response_text = qwen_intent_recognition(text, conversation_history)
        if not response_text:
            raise HTTPException(status_code=400, detail="意图识别或对话管理失败，未获取到有效回复内容")
        logging.info(f"意图识别和对话管理成功，回复内容: {response_text}")
        # 音频生成
        data = {
            'tts_text': response_text,
            'spk_id': '中文男'
        }
        from audio_playback import play_audio_from_stream
        audio_response = await play_audio_from_stream(config.COSY_VOICE_URL, data)
        logging.info('音频生成成功')
        if not audio_response:
            raise HTTPException(status_code=400, detail="音频生成失败，未获取到有效音频数据")

        # 返回音频和文字，使用字典包装文字内容，以二进制形式返回音频数据
        return Response(content=audio_response, media_type="audio/wav")
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"出现未知错误: {e}")
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    host = os.getenv('APP_HOST', '0.0.0.0')  # 优先从环境变量获取，默认值为 0.0.0.0
    port = int(os.getenv('APP_PORT', 9000))  # 优先从环境变量获取，默认值为 9000
    try:
        uvicorn.run(app, host=host, port=port, log_level="info")
    except Exception as e:
        logging.error(f"启动 FastAPI 应用出错: {e}")